package com.tianji.learning.service.impl;

import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsRecord;
import com.tianji.learning.domain.vo.PointsStatisticsVO;
import com.tianji.learning.enums.PointsRecordType;
import com.tianji.learning.mapper.PointsRecordMapper;
import com.tianji.learning.mq.message.PointsMessage;
import com.tianji.learning.service.IPointsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 学习积分记录，每个月底清零 服务实现类
 * </p>
 *
 * @author yp
 * @since 2024-07-30
 */
@Service
@RequiredArgsConstructor
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements IPointsRecordService {

    private final StringRedisTemplate redisTemplate;

    /**
     * 添加学习积分记录
     *
     * @param message
     * @param type
     */
    @Override
    public void addPointsRecord(PointsMessage message, PointsRecordType type) {
        //1.判断当前业务类型是否有积分上限
        int maxPoints = type.getMaxPoints();
        Long userId = message.getUserId();
        Integer points = message.getPoints();
        int realPoint = points;
        LocalDateTime now = LocalDateTime.now();
        if (maxPoints > 0) {
            //2.有积分上限
            //2.2查询当前用户今日某种类型的业务易经获得积分
//      SELECT SUM(points) from points_record WHERE user_id = 2 and create_time > '2022-10-10 0:00:00' and create_time < '2023-10-10 0:00:00' and type = 1
            LocalDateTime begin = DateUtils.getDayStartTime(now);
            LocalDateTime end = DateUtils.getDayEndTime(now);
            int todayPoints = getBaseMapper().queryUserTodayPoint(userId, type, begin, end);
            //2.3判断是否超过积分上限
            if (todayPoints >= maxPoints) {
                return;
            }
            if (todayPoints + points > maxPoints) {
                realPoint = maxPoints - todayPoints;
            }

        }
        //保存记录
        PointsRecord pointsRecord = new PointsRecord();
        pointsRecord.setUserId(userId);
        pointsRecord.setPoints(realPoint);
        pointsRecord.setType(type);
        save(pointsRecord);


        //4.分数【累加】到Redis的Zset中 前缀：2023.07 用户id 分数
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        redisTemplate.opsForZSet().incrementScore(key, userId.toString(), realPoint);
    }

    /**
     * 查询今天的积分的接口
     *
     * @return
     */
    @Override
    public List<PointsStatisticsVO> queryMyPointToday() {
        //获取当前用户
        Long userId = UserContext.getUser();
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime begin = DateUtils.getDayStartTime(now);
        LocalDateTime end = DateUtils.getDayEndTime(now);
        //调用dao
        List<PointsRecord> pointsRecords = getBaseMapper().queryMyPointToday(userId, begin, end);
        if (CollUtils.isEmpty(pointsRecords)) {
            return CollUtils.emptyList();
        }
        //4.封装Vo
        List<PointsStatisticsVO> pointLists = new ArrayList<>();
        for (PointsRecord pointsRecord : pointsRecords) {
            PointsStatisticsVO vo = new PointsStatisticsVO();
            vo.setType(pointsRecord.getType().getDesc());
            vo.setMaxPoints(pointsRecord.getType().getMaxPoints());
            vo.setPoints(pointsRecord.getPoints());
            pointLists.add(vo);
        }
        return pointLists;
    }
}
